﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WJP.Logging;
using WJP.Queue.Remoting;

namespace WJP.Queue.NameServer
{
    /// <summary>
    /// 名称服务控制器
    /// </summary>
    public class NameServerController
    {
        private readonly SocketRemotingServer socketRemotingServer;
        private bool _isShuttingdown = true;

        public NameServerSetting Setting { get; private set; }

        public ClusterManager ClusterManager { get; private set; }

        public NameServerController(Action<NameServerSetting> setting = null)
        {
            Setting = new NameServerSetting();
            setting?.Invoke(Setting);


        }

        /// <summary>
        /// 启动名称服务
        /// </summary>
        /// <returns></returns>
        public NameServerController Start()
        {
            var watch = Stopwatch.StartNew();
            LogManager.Logger.InfoFormat("名称服务启动中...");

            ClusterManager.Start();
            socketRemotingServer.Start();
            _isShuttingdown = false;

            LogManager.Logger.InfoFormat("名称服务已启动，耗时：{0}毫秒,绑定地址：{1}", watch.ElapsedMilliseconds, Setting.BindingAddress);
            return this;
        }

        /// <summary>
        /// 关闭名称服务
        /// </summary>
        /// <returns></returns>
        public NameServerController Shutdown()
        {
            if (!_isShuttingdown)
            {
                var watch = Stopwatch.StartNew();
                LogManager.Logger.InfoFormat("名称服务开始关闭，绑定地址为：{0}", Setting.BindingAddress);
                socketRemotingServer.Shutdown();
                ClusterManager.Shutdown();
                _isShuttingdown = true;
                LogManager.Logger.InfoFormat("名称服务器成功关闭，耗时：{0}毫秒", watch.ElapsedMilliseconds);
            }
            return this;
        }

        /// <summary>
        /// 注册请求处理方法
        /// </summary>
        private void RegisterRequestHandlers()
        {

        }
    }
}
